package com.youoor.interceptors;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.fasterxml.jackson.databind.ObjectMapper;



public class LogsInterceptor extends HandlerInterceptorAdapter {
//	private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
	
	private static final Logger paramsLogger = Logger.getLogger("params");
	
	private ObjectMapper objectMapper = new ObjectMapper();

	
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {  
        Long beginTime = System.currentTimeMillis();
        request.setAttribute("method-startTime", beginTime);
        return true;  
    }  
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		Map<String, Object> logJson = new HashMap<String, Object>();
		
		// userId
		Object userId = request.getHeader("kp-inner-userid");
			
		String methodName = null;
		
		if(handler instanceof HandlerMethod && ((HandlerMethod)handler).getMethod() != null) {
			methodName = ((HandlerMethod) handler).getMethod().getName();
		}
		
		
		String ip = this.getRemortIP(request);
		String px_ip = request.getRemoteAddr();		

		
		logJson.put("t", "REQUEST");
		logJson.put("f", methodName);
		logJson.put("r", request.getAttribute("returnValue"));
		logJson.put("uid", userId);
		logJson.put("ip", ip);
		logJson.put("px_ip", px_ip);
		logJson.put("ua", request.getHeader("User-Agent"));
		logJson.put("p", this.getFormatParamsForP(request.getAttribute("attributeMap")));
		logJson.put("h", this.parseHeader(request));
		logJson.put("ct", this.getConsumeTime(request));
		String nowTime = sdf.format(new Date());
		
//		logger.info(nowTime + " - " +  objectMapper.writeValueAsString(logJson));
		paramsLogger.info(nowTime + " - " +  objectMapper.writeValueAsString(logJson));
	}

	public Map getFormatParamsForP(Object paramsData){
		try {
			if (paramsData != null) {
				Map<String, Object> res = (Map<String, Object>) (paramsData);
//				if (res.containsKey("device_info")) {
//					res.remove("device_info");
//				}
//				if (res.containsKey("sms_list")) {
//					res.remove("sms_list");
//				}
//				if (res.containsKey("calllogs")) {
//					res.remove("calllogs");
//				}
				return res;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		return null;
	}
	
	public Map getFormatParamsForR(Object retData){
		try {
			if (retData != null) {
				Map<String, Object> res = (Map<String, Object>) (retData);
//				if (res.containsKey("calllogs")) {
//					res.remove("calllogs");
//				}
//				if (res.containsKey("sms_list")) {
//					res.remove("sms_list");
//				}
//				if (res.containsKey("threads")) {
//					res.remove("threads");
//				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		return null;
	}
	
	
	public String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}
	
	private long getConsumeTime(HttpServletRequest request){
		long endTime = System.currentTimeMillis();//2、结束时间  
        long beginTime = (Long)request.getAttribute("method-startTime");//得到线程绑定的局部变量（开始时间）  
        long consumeTime = endTime - beginTime;//3、消耗的时间  
        return consumeTime;
	}
	
	private Map<String,Object> parseHeader(HttpServletRequest request){
		Enumeration headerNames = request.getHeaderNames();
		Map<String,Object> headerParams = new HashMap<String,Object>();
		while (headerNames.hasMoreElements()) {
			String headerName = String.valueOf(headerNames.nextElement());
			
			if(headerName != null && headerName.startsWith("kp-")) {
				headerParams.put(headerName.replace("-", "_"), request.getHeader(headerName));
			}
		}
		return headerParams;
	}
	
	private Map<String,Object> getAllAttributes(HttpServletRequest request) {
		
		Object attribute = request.getAttribute("attributeMap");
		if(attribute!= null && attribute instanceof Map) {
			Map<String,Object> attributeMap = (Map<String,Object>)attribute;
			return attributeMap;
		}
		return null;		
	}


}
